package com.zoro.dyformservice.constants.response.common;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.zoro.dyformservice.support.web.converter.CustomJsonSerializer;
import com.zoro.dyformservice.support.web.converter.CustomJsonSerializerType;

import java.io.IOException;

@CustomJsonSerializerType(use = Sex.SexJsonSerializerProvider.class)
public enum Sex {
    MALE("1", "男"),
    FEMALE("2", "女");
    public final String code;
    public final String name;

    Sex(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public static Sex getByCode(String code) {
        if (code == null) {
            return null;
        }

        for (Sex sex : Sex.values()) {
            if (code.equals(sex.code)) {
                return sex;
            }
        }
        return null;
    }

    public static class SexJsonSerializerProvider implements CustomJsonSerializer<Sex> {

        @Override
        public JsonSerializer<Sex> serializer() {
            return new JsonSerializer<>() {
                @Override
                public void serialize(Sex value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                    if (value == null) {
                        return;
                    }

                    gen.writeString(value.code);
                }
            };
        }

        @Override
        public JsonDeserializer<Sex> deserializer() {
            return new JsonDeserializer<>() {
                @Override
                public Sex deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                    String text = p.getText();
                    if (text == null) {
                        return null;
                    }
                    for (Sex sex : Sex.values()) {
                        if (text.equals(sex.code)) {
                            return sex;
                        }
                    }
                    return null;
                }
            };
        }
    }
}
